package com.example.nettry.demo.repair;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Eastern unbeaten
 * @email chenshiyun2011@163.com
 * @date 2019-10-04 13:53
 */
public class TimeServer {

    public static void main(String[] args) {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf (args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new TimeServer ( ).bind (8080);
    }

    public void bind(int port) {
        //配置服务端的Nio线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup ( );
        NioEventLoopGroup workerGroup = new NioEventLoopGroup ( );
        try {
            //
            ServerBootstrap b = new ServerBootstrap ( );
            //设置
            b.group (bossGroup, workerGroup)
                    .channel (NioServerSocketChannel.class)
                    .option (ChannelOption.SO_BACKLOG, 1014)
                    //
                    .childHandler (new ChildChannelHandler ( ));
            //绑定端口,同步等待成功
            ChannelFuture f = b.bind (port).sync ( );
            //等待服务端监听端口关闭
            f.channel ( ).closeFuture ( ).sync ( );
        } catch (InterruptedException e) {
            e.printStackTrace ( );
        } finally {
            //释放资源
            bossGroup.shutdownGracefully ( );
            workerGroup.shutdownGracefully ( );
        }

    }
}
